package com.tao.com.xiaowen.module.main;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.facebook.drawee.view.SimpleDraweeView;
import com.tao.com.xiaowen.config.http.MyJson;
import com.tao.com.xiaowen.config.tecent.BaseUiListener;
import com.tao.com.xiaowen.config.tecent.GetUserAuth;
import com.tao.com.xiaowen.module.me.LoginActivity;
import com.tao.com.xiaowen.module.me.MyFavoriteActivity;
import com.tao.com.xiaowen.model.Model;
import com.tao.com.xiaowen.event.UserAuthEvent;
import com.tao.com.xiaowen.event.UserInfoEvent;
import com.tao.com.xiaowen.model.UserInfos;
import com.tao.com.xiaowen.R;
import com.tao.com.xiaowen.module.me.UserInfoActivity;
import com.tencent.connect.UserInfo;
import com.tencent.tauth.Tencent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobUser;

/**
 * Created by Administrator on 2016/8/1.
 */
public class MeFragment extends Fragment implements View.OnClickListener {
    private Tencent tencent;
    private UserInfo userInfo;
    private long time = 0;
    private String expires_in = null;
    private BmobUser bmobUser;

    private int versionCode;
    private AlertDialog dialog;

    private RelativeLayout userLogin;
    private RelativeLayout checkVersion;
    private RelativeLayout myFavorite;
    private View view;
    private TextView titleView;
    private TextView userNameView;
    private TextView textLoginView;
    private SimpleDraweeView userPicView;
    private Button userLoginOutView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_me, container, false);
//        Bmob.initialize(getActivity(), Model.APP_ID_BMOB);
        tencent = Tencent.createInstance(Model.APP_ID_QQ, getActivity().getApplication());
        EventBus.getDefault().register(this);

        initView();
        initQqUserInfo();
        initUserInfo();
        return view;
    }

    private void initView() {
        userLogin = (RelativeLayout) view.findViewById(R.id.user_login);
        checkVersion = (RelativeLayout) view.findViewById(R.id.version_check);
        myFavorite = (RelativeLayout) view.findViewById(R.id.my_favorite);
        titleView = (TextView) view.findViewById(R.id.title);
        userNameView = (TextView) view.findViewById(R.id.user_name);
        textLoginView = (TextView) view.findViewById(R.id.login_text);
        userPicView = (SimpleDraweeView) view.findViewById(R.id.user_picture);
        userLoginOutView = (Button) view.findViewById(R.id.user_login_out);

        titleView.setText(R.string.my_setting);
        userPicView.setImageURI("http://img2.imgtn.bdimg.com/it/u=2474223988,1358834824&fm=23&gp=0.jpg");

        userLogin.setOnClickListener(this);
        checkVersion.setOnClickListener(this);
        userLoginOutView.setOnClickListener(this);
        myFavorite.setOnClickListener(this);

    }

    private void initUserInfo() {
        bmobUser = GetUserAuth.getUserAth(getActivity());
        if (bmobUser != null) {
            Message message = handler.obtainMessage();
            message.what = Model.USER_INFO;
            handler.sendMessage(message);
        } else {
            userLoginOutView.setVisibility(View.INVISIBLE);
        }
    }

    private void initQqUserInfo() {
        expires_in = GetUserAuth.getUserAyth(tencent, getActivity());
        if (expires_in != null) {
            time = System.currentTimeMillis() + Long.parseLong(expires_in) * 1000;
        } else {
            time = 0;
            userLoginOutView.setVisibility(View.INVISIBLE);
        }

        if (time > 0) {
            userInfo = new UserInfo(getActivity(), tencent.getQQToken());
            userInfo.getUserInfo(new BaseUiListener() {
                @Override
                public void onComplete(Object o) {
                    super.onComplete(o);
                    Message message = handler.obtainMessage();
                    message.what = Model.USER_QQ_INFO;
                    message.obj = o;
                    handler.sendMessage(message);
                }
            });
        } else {
            Message message = handler.obtainMessage();
            message.what = Model.USER_INFO_ERR;
            handler.sendMessage(message);
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Model.USER_INFO_ERR:
                    break;
                case Model.USER_INFO:
                    String name = (String) BmobUser.getObjectByKey("username");
                    textLoginView.setVisibility(View.INVISIBLE);
                    userNameView.setText(name);
                    if (time > 0 || bmobUser != null) {
                        userPicView.setImageURI("http://img2.imgtn.bdimg.com/it/u=2474223988,1358834824&fm=23&gp=0.jpg");
                    }

                    userLoginOutView.setVisibility(View.VISIBLE);
                    break;
                case Model.USER_QQ_INFO:
                    Object object = msg.obj;
                    UserInfos userInfos = MyJson.getUserInfoJson(object);
                    textLoginView.setVisibility(View.INVISIBLE);
                    userNameView.setText(userInfos.getNickname());
                    userPicView.setImageURI(userInfos.getFigureurl_qq_1());
                    userLoginOutView.setVisibility(View.VISIBLE);
                    break;
                case Model.SHOWUPDATEDIALOG:
                    showUpdateDialog();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.user_login:
                if (time > 0 || bmobUser != null) {
                    Intent intent = new Intent(getActivity(), UserInfoActivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.my_favorite:
                if (time > 0 || bmobUser != null) {
                    Intent intent = new Intent(getActivity(), MyFavoriteActivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                }

                break;
            case R.id.version_check:
                getVersionName();
                checkVersion();
                break;
            case R.id.user_login_out:
                tencent.logout(getActivity());
                BmobUser.logOut();
                EventBus.getDefault().post(new UserInfoEvent());
                EventBus.getDefault().post(new UserAuthEvent());
                userLoginOutView.setVisibility(View.INVISIBLE);
                refreshFragment();
                break;
            default:
                break;
        }
    }

    private void checkVersion() {
        Message message = handler.obtainMessage();
        message.what = getNewVersion();
        handler.sendMessage(message);
    }

    private void refreshFragment() {
        MeFragment meFragment = new MeFragment();
        getActivity().getSupportFragmentManager().beginTransaction().remove(MainActivity.currentFragment).add(R.id.framelayout, meFragment).commit();
        MainActivity.currentFragment = meFragment;
    }

    //获取当前程序的版本号
    private String getVersionName() {
        PackageManager packageManager = getActivity().getPackageManager();
        PackageInfo packageInfo = null;
        try {
            packageInfo = packageManager.getPackageInfo(getActivity().getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        versionCode = packageInfo.versionCode;
        return packageInfo.versionName;
    }

    // 获取服务器设置的版本
    private int getNewVersion() {

        int serverCode = 1;
        if (serverCode == versionCode) {
            Toast.makeText(getActivity(), "已经是最新的版本!", Toast.LENGTH_SHORT).show();
        } else {
            return Model.SHOWUPDATEDIALOG;
        }
        return serverCode;
    }

    private void showUpdateDialog() {
        AlertDialog.Builder builer = new AlertDialog.Builder(getActivity());
        builer.setTitle("版本升级");
        builer.setMessage("11111");
        builer.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Log.d("11111", "下载apk,更新");
            }
        });
        builer.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        AlertDialog dialog = builer.create();
        dialog.show();
    }

    private void downLoadNewApk() {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUserInfoEvent(UserInfoEvent event) {
        initQqUserInfo();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUserAuthEvent(UserAuthEvent event) {
        initUserInfo();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
